
import pandas as pd
import copy
import utils
import sys
sys.path.append('./')

from src.models_new import visualizations

# When running this file usually also add argument which is the path for the table
try:
    overleaf_path = sys.argv[1]
except:
    overleaf_path = './../Apps/Overleaf/bbm/draft/reports/revision/'

#%% READ IN DATA ------------------------------------------------------------------------
df = pd.read_csv(
    './data_py/processed/contracts_final.csv',
    index_col=[0]
)
df_gas = pd.read_csv('./data_py/processed/gas_prices_deflated.csv',
                     index_col=[0], parse_dates=['month'])
df_gas = df_gas[df_gas['month'].dt.year <= 2009]

df_oil = pd.read_csv('./data_py/processed/oil_prices_deflated.csv', index_col=[0])
df_gas['month'] = pd.to_datetime(df_gas['month'])

#%% GET % OIL VS GAS --------------------------------------------------------------------
# Oil is measured in barrels
total_oil_volume = df['oil_volume'].sum()

# Gas in measured in thousands of cubic feet (MCF)
total_gas_volume = df['gas_volume'].sum()

# According to investopedia: One barrel of crude oil generally has
# approximately the same energy content as 6,000 cubic feet of natural gas,
# so this quantity of natural gas is "equivalent" to one barrel of oil.

total_gas_volume_boe = total_gas_volume / 6
gas_prop = total_gas_volume_boe / (total_gas_volume_boe + total_oil_volume)
df_gas['price_average'] = gas_prop * df_gas['gas'] + (1 - gas_prop) * df_oil['brent']

# If normalize 'value' to 1, then it's predicted path:
df_gas['quantity_all_gas'] = (1.0 / df_gas['gas'].mean()) * df_gas['gas']
df_gas['quantity_prop'] = gas_prop * (1.0 / df_gas['gas'].mean()) * df_gas['gas'] \
                + (1 - gas_prop) * (1.0 / df_oil['brent'].mean()) * df_oil['brent']

df['prop'] = (df['gas_volume'] / 6.0) / (df['oil_volume'] + (df['gas_volume'] / 6.0))
df_prop = copy.deepcopy(df)

#%% DO GRAPHS ---------------------------------------------------------------------------
import importlib
importlib.reload(visualizations)
visualizations.graph_oil_vs_gas(
    df_prop, df_gas, output_path=overleaf_path + 'figures/oil_gas_het.pdf')


#%% DO REGRESSIONS ----------------------------------------------------------------------
formulas_by_reg = dict()
formulas_by_reg[0] = 'mri ~ prop'
formulas_by_reg[1] = 'mri ~ prop + C(year) + C(month)'
formulas_by_reg[2] = 'mri ~ prop + C(year) + C(month) + tau + C(reneg) + C(spec)'
coefs_to_tex_names = {
    'prop': 'prop'
}
path_tex_skeleton = './src/tex/table_proportion_gas.tex'
path_tex_output = overleaf_path + 'tables/table_proportion_gas.tex'

df['year'] = pd.to_datetime(df['fixture_date']).dt.year
df['month'] = pd.to_datetime(df['fixture_date']).dt.month

utils.build_ols_table(
    formulas_by_reg, df, coefs_to_tex_names, path_tex_skeleton, path_tex_output
)
